package com.zlx.store.goods.service.impl;

import com.zlx.store.common.config.RedisConfig;
import com.zlx.store.goods.service.HotGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Set;

@Service
public class HotGoodsServiceImpl implements HotGoodsService {
    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    @Override
    public List<Long> addHotGoods(List<Long> ids) {

        if (redisTemplate.hasKey("hotGoods_manual")) {
            //重复的goods不变
            for (Long id:ids){
                if (Objects.nonNull(redisTemplate.opsForZSet().score("hotGoods_manual", id))) {
                    ids.remove(id);
                }
            }
            //使"hotGoods_manual"保持三个
            int currentCount = redisTemplate.opsForZSet().zCard("hotGoods_manual").intValue();
            int listCount = ids.size();
            if (currentCount + listCount > 3) {
                int end=0;
                if (currentCount>currentCount + listCount - 4){
                    end=currentCount + listCount - 4;
                }
                else {
                    end =currentCount-1;
                }
                Set<Object> members = redisTemplate.opsForZSet().range("hotGoods_manual", 0,end);
                redisTemplate.opsForZSet().remove("hotGoods_manual", members.toArray());
            }
        }
        //添加"hotGoods_manual"
        for (Long id:ids){
            Double count=redisTemplate.opsForZSet().score("hotGoods_auto",id);
            if (Objects.isNull(count)){
                count=0.0;
            }
            redisTemplate.opsForZSet().remove("hotGoods_auto",id);
            redisTemplate.opsForZSet().add("hotGoods_manual",id,count);
        }
        return ids;
    }
}
